import Scanner from './Scanner';
/**
 * 转换为tokens
 * @param {*} templateStr 
 * @returns 
 */
export function parseTokens(templateStr) {
    var tokens = [];
    var scanner = new Scanner(templateStr);
    var words;
    while (!scanner.eos()) {
        words = scanner.scanUtil("{{");
        if (words != '') {
            tokens.push(["text", words]);
        }
        scanner.scan("{{");
        words = scanner.scanUtil("}}");
        if (words != '') {
            //words为{{}}里面内容，判断是否含有#
            if (words.indexOf("#") == 0) {
                tokens.push(["#", words.substring(1)]);
            } else if (words.indexOf("/") == 0) {
                tokens.push(["/", words.substring(1)]);
            } else {
                tokens.push(["name", words])
            }
        };
        scanner.scan("}}");
    }
    return tokens;
}

/**
 * 折叠tokens
 * @param {Array} tokens 
 */
export function nestTokens(tokens) {
    var nestTokens = [];
    //收集器，默认指向nestTokens,收集器不断变化
    var collector = nestTokens;
    //栈结构,存放小tokens
    var sections = [];

    for (let index = 0; index < tokens.length; index++) {
        const token = tokens[index];
        switch (token[0]) {
            case "#":
                //收集子元素
                collector.push(token);
                //入栈
                sections.push(token);
                // console.log(token[1] + "入栈了");
                //收集器变化，给token添加下表为2的项，收集器指向它
                collector = token[2] = [];
                break;

            case "/":
                //出栈
                sections.pop(token);
                // console.log(token[1] + "出栈了");
                //改变收集器
                collector = sections.length > 0 ? sections[sections.length - 1][2] : nestTokens;
                break;

            default:
                collector.push(token);
                break;
        }

    }
    return nestTokens;
}